package com.longsunhd.yum.buffalo.network;

import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.longsunhd.yum.buffalo.base.BaseApplication;
import com.longsunhd.yum.buffalo.network.api.BaseApi;
import com.longsunhd.yum.buffalo.network.cookie.PersistentCookieStore;

import java.io.File;
import java.io.IOException;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
/**
 * Created by 黄宣淇
 * on 2020/9/30 0030.
 * 代码如果不加注释，只有上帝和自己知道--鲁迅
 */
public class ApiFactory {
    //  public static final String YUM_ROOT_URL = "https://ply3.guiwang.org/";
     public static final String YUM_ROOT_URL = "https://wlwadmin.longsunhd.com/";

    private static String TAGStr="HttpLog";
    private static final long cacheSize = 1024 * 1024 * 20;// 缓存文件最大限制大小20M
    private static String cacheDirectory = Environment.getExternalStorageDirectory() + "/okttpcaches"; // 设置缓存文件路径
    private static Cache cache = new Cache(new File(cacheDirectory), cacheSize);  //    private static String TAGStr="HttpLog";
    private static final int TimeOut=30;
    public static ApiFactory instance;

    public static ApiFactory newInstance(){
     /*   if (instance == null) {
            synchronized (ApiFactory.class) {
                if (instance == null) {
                    instance = new ApiFactory();
                }
            }
        }*/
        instance = new ApiFactory();
        init();
        return instance;
    }
    private static String token="";
    public static ApiFactory newInstance(String token1){
        token=token1;
        instance = new ApiFactory();
        init();
        return instance;
    }
    private static OkHttpClient okHttpClient;

    //持久化cookie
    private static CookieManager cookieManager;

  //  private static Converter.Factory gsonConverterFactory = GsonConverterFactory.create();
  private static Converter.Factory gsonConverterFactory = GsonConverterFactory.create();
    private static CallAdapter.Factory rxJavaCallAdapterFactory = RxJava2CallAdapterFactory.create();
    private static class HttpLogger implements HttpLoggingInterceptor.Logger {
        @Override
        public void log(String message) {
            Log.i(TAGStr, message);
        }
    }
    private static void init(){
        //如果无法生存缓存文件目录，检测权限使用已经加上，检测手机是否把文件读写权限禁止了
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        builder.connectTimeout(TimeOut, TimeUnit.SECONDS); // 设置连接超时时间
        builder.writeTimeout(TimeOut, TimeUnit.SECONDS);// 设置写入超时时间
        builder.readTimeout(TimeOut, TimeUnit.SECONDS);// 设置读取数据超时时间
        builder.retryOnConnectionFailure(true);// 设置进行连接失败重试

        builder.cache(cache);// 设置缓存
        //添加网络日志拦截器
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger());
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(logInterceptor);

        cookieManager = new CookieManager(new PersistentCookieStore(BaseApplication.getInstance()), CookiePolicy.ACCEPT_ALL);
        builder.cookieJar(new JavaNetCookieJar(cookieManager));
        if(!TextUtils.isEmpty(token)){
            builder.addInterceptor(new Interceptor() {
                @NonNull
                @Override
                public Response intercept(@NonNull Chain chain) throws IOException {
                    Request request = chain.request()
                            .newBuilder()
                            .addHeader("Authorization", token)
                            .build();
                    return chain.proceed(request);

                }
            });
        }

        okHttpClient = builder.build();
    }


    /*构造网络链接的代理类，通过泛型限制api的类型，不用请求每个API都要构造一遍相同代码*/
    public  <baseApi extends BaseApi>  baseApi  getApi(Class<baseApi> clz){
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(YUM_ROOT_URL)
                .addConverterFactory(new NullOnEmptyConverterFactory())
                .addConverterFactory(gsonConverterFactory)
                .addCallAdapterFactory(rxJavaCallAdapterFactory)
                .build();

        BaseApi product=null;

        product = retrofit.create(clz);
        return (baseApi) product;
    }
    /*构造网络链接的代理类，通过泛型限制api的类型，不用请求每个API都要构造一遍相同代码*/
    public  <baseApi extends BaseApi> baseApi  getApi(Class<baseApi> clz,String baseUrl){
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(baseUrl)
                .addConverterFactory(new NullOnEmptyConverterFactory())
                .addConverterFactory(gsonConverterFactory)
                .addCallAdapterFactory(rxJavaCallAdapterFactory)
                .build();

        BaseApi product=null;

        product = retrofit.create(clz);
        return (baseApi) product;
    }
}
